package com.aiflow.system;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONObject;

import util.ServletHelp;
import util.StringUtils;

import com.aiflow.bean.FrontUser;
import com.aiflow.bean.User;
import com.aiflow.db.ConnDB;
import com.aiflow.util.MD5;
import com.opensymphony.xwork2.ActionSupport;

public class loginAction extends ActionSupport{
	
	public void postLoginAction() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		String userName = request.getParameter("userId");
		String pwd = request.getParameter("password");
		response.setContentType("text/html;charset=utf-8");//针对url提交的乱码处理
		ConnDB db = new ConnDB();
		pwd  = MD5.encryptMD5(pwd);
		JSONObject re = new JSONObject();
		boolean hasLogin = db.valilogin(userName, pwd);
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(hasLogin) {
			//TODO:如果登录成功的话保持用户信息
//			request.getSession().setAttribute("userName", userName);
//			request.getSession().setAttribute("password", pwd);
//			request.getSession().setAttribute("hasLogined", "true");
			//TODO:从数据库查找出当权用户的菜单，保存至session中
			FrontUser use = db.returnUser(userName);
			request.getSession().setAttribute("user" , use);
			re.put("success", true);
		    re.put("message", "成功");
		    out.print(re.toString());
		    out.close();
		}else {
			re.put("success", false);
			re.put("message", "用户名或密码错误");
			out.print(re.toString());
			out.close();
		}
	}
	
	public String getLoginAction(HttpServletRequest request,HttpServletResponse response) {
		String userName = request.getParameter("userName");
		String pwd = request.getParameter("password");
		if(StringUtils.isEmpty(userName)&&StringUtils.isEmpty(pwd)) {
			userName = request.getSession().getAttribute("userName")==null?"":request.getSession().getAttribute("userName").toString();
			pwd = request.getSession().getAttribute("password") == null?"":request.getSession().getAttribute("password").toString();
		}
		ConnDB db = new ConnDB();
		pwd  = MD5.encryptMD5(pwd);
		JSONObject re = new JSONObject();
		boolean hasLogin = db.valilogin(userName, pwd);
		if(hasLogin) {
			//TODO:如果登录成功的话保持用户信息
			request.getSession().setAttribute("userName", userName);
			request.getSession().setAttribute("password", pwd);
			request.getSession().setAttribute("hasLogined", "true");
			//TODO:从数据库查找出当权用户的菜单，保存至session中
			FrontUser use = db.returnUser(userName);
			request.getSession().setAttribute("user" , use);
			re.put("success", true);
		    re.put("message", "成功");
			return "index";
		}else {
			re.put("success", false);
			re.put("message", "用户名或密码错误");
			return "login";
		}
	} 
	
	//清空session
	public void logout()
    throws Exception
  {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    request.getSession().removeAttribute("user");
    JSONObject res = new JSONObject();
    res.put("success", Boolean.valueOf(true));
    ServletHelp.outRequestForJson(request, response, res.toString());
  }

	  //获取用户对象
	  public User getUserWithMetaByUserId(String userName){
		    User user = new User();
			ConnDB db = new ConnDB();
			ResultSet rs = null;
			Connection con =  db.getConnection();
			PreparedStatement ps = null;
			try {
				String sql = "select id,login_acct,login_pass,name,role_id,dept_id,state,add_time,expired_time from user_t where Login_name=?'";
				ps = con.prepareStatement(sql);
				ps.setString(1,userName);
				rs = ps.executeQuery();
				while (rs.next()) {
					user.setId(rs.getString(1));
					user.setLogin_acct(rs.getString(2));
					user.setLogin_pass(rs.getString(3));
					user.setName(rs.getString(4));
					user.setRole_id(rs.getString(5));
					user.setDept_id(rs.getString(6));
					user.setState(rs.getString(7));
					user.setAdd_time(rs.getString(8));
					user.setExpired_time(rs.getString(9));
				}
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally
			{
	            try
	            {
	            	ps.close();
	            	rs.close();
	            	con.close();
	            }
	            catch(Exception ex1)
	            {
	                ex1.printStackTrace();
	            }
	       }
		    return user; 
	  }
	
	//特殊登录的验证,直接输入地址跳转到指定的页面,例如(http://10.30.164.235:8080/VoiceTranslator/specialLoginAction.action?userId=zhuxianbo&password=123)
	  public void specialLoginAction() {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpServletResponse response = ServletActionContext.getResponse();
			String userName = request.getParameter("userId");
			String pwd = request.getParameter("password");
			response.setContentType("text/html;charset=utf-8");//针对url提交的乱码处理
			ConnDB db = new ConnDB();
			pwd  = MD5.encryptMD5(pwd);
			boolean hasLogin = db.valilogin(userName, pwd);
			if(hasLogin) {
				//TODO:从数据库查找出当权用户的菜单，保存至session中
				FrontUser use = db.returnUser(userName);
				request.getSession().setAttribute("user" , use);
			    try {
					response.sendRedirect("http://10.30.164.235:8080"+request.getContextPath() + "/index.jsp");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
